'use client';

import React, { useState, useEffect } from 'react';
import { useCollaboration } from '@/hooks/use-collaboration';
import { useSocket } from '@/hooks/use-socket';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { UserInfo, UserActivity } from '@/types/socket';
import { Clock, Edit, Eye, MessageSquare, AlertCircle } from 'lucide-react';

interface CollaborationStatusProps {
  projectId?: string;
  documentId?: string;
  collaborators?: { id: string; name: string; image?: string; status?: string }[];
  className?: string;
}

export function CollaborationStatus({ 
  projectId, 
  documentId, 
  collaborators = [],
  className = '' 
}: CollaborationStatusProps) {
  const { activeUsers, lockedNodes } = useCollaboration();
  const { isConnected, connectionState } = useSocket();
  const [userActivities, setUserActivities] = useState<Record<string, { activity: UserActivity; timestamp: number }>>({});
  
  // 监听用户活动
  useEffect(() => {
    const socket = useSocket();
    
    // 处理用户活动更新
    const handleUserActivity = (data: any) => {
      if (data.projectId !== projectId) return;
      
      setUserActivities(prev => ({
        ...prev,
        [data.userId]: {
          activity: data.activity,
          timestamp: Date.now()
        }
      }));
    };
    
    // 处理用户状态变化
    const handleUserStatusChanged = (data: any) => {
      if (data.status === 'offline') {
        // 如果用户离线，从活动列表中移除
        setUserActivities(prev => {
          const newActivities = { ...prev };
          delete newActivities[data.userId];
          return newActivities;
        });
      }
    };
    
    // 订阅事件
    const unsubActivity = socket.onUserActivity(handleUserActivity);
    const unsubStatus = socket.onUserStatusChanged(handleUserStatusChanged);
    
    return () => {
      unsubActivity();
      unsubStatus();
    };
  }, [projectId]);
  
  // 获取用户活动图标和颜色
  const getUserActivityInfo = (activity: UserActivity) => {
    switch (activity) {
      case 'editing':
        return { icon: <Edit className="h-3 w-3" />, color: 'bg-blue-500', label: '编辑中' };
      case 'viewing':
        return { icon: <Eye className="h-3 w-3" />, color: 'bg-green-500', label: '查看中' };
      case 'commenting':
        return { icon: <MessageSquare className="h-3 w-3" />, color: 'bg-amber-500', label: '评论中' };
      case 'suggesting':
        return { icon: <AlertCircle className="h-3 w-3" />, color: 'bg-purple-500', label: '建议中' };
      default:
        return { icon: <Clock className="h-3 w-3" />, color: 'bg-gray-500', label: '空闲' };
    }
  };
  
  // 获取用户初始字母（用于头像）
  const getUserInitials = (name: string) => {
    return name
      .split(' ')
      .map(part => part[0])
      .join('')
      .toUpperCase()
      .substring(0, 2);
  };
  
  // 渲染连接状态
  const renderConnectionStatus = () => {
    if (!isConnected) {
      return (
        <Badge variant="outline" className="bg-red-100 text-red-800 border-red-200">
          {connectionState.error ? '连接错误' : '未连接'}
        </Badge>
      );
    }
    
    return (
      <Badge variant="outline" className="bg-green-100 text-green-800 border-green-200">
        已连接
      </Badge>
    );
  };
  
  // 渲染活跃用户列表
  const renderActiveUsers = () => {
    if (activeUsers.length === 0) {
      return (
        <div className="text-sm text-muted-foreground">
          暂无其他用户在线
        </div>
      );
    }
    
    return (
      <div className="flex flex-wrap gap-1">
        <TooltipProvider>
          {activeUsers.map(user => {
            const activity = userActivities[user.id]?.activity || 'idle';
            const { icon, color, label } = getUserActivityInfo(activity);
            
            return (
              <Tooltip key={user.id}>
                <TooltipTrigger asChild>
                  <div className="relative">
                    <Avatar className="h-8 w-8">
                      {user.image ? (
                        <AvatarImage src={user.image} alt={user.name} />
                      ) : (
                        <AvatarFallback>{getUserInitials(user.name)}</AvatarFallback>
                      )}
                    </Avatar>
                    <span className={`absolute -bottom-1 -right-1 rounded-full ${color} p-1`}>
                      {icon}
                    </span>
                  </div>
                </TooltipTrigger>
                <TooltipContent>
                  <p>{user.name}</p>
                  <p className="text-xs text-muted-foreground">{label}</p>
                </TooltipContent>
              </Tooltip>
            );
          })}
        </TooltipProvider>
      </div>
    );
  };
  
  // 渲染锁定节点信息
  const renderLockedNodes = () => {
    const lockedNodesList = Object.entries(lockedNodes);
    
    if (lockedNodesList.length === 0) {
      return null;
    }
    
    return (
      <div className="mt-2">
        <h4 className="text-sm font-medium">锁定的内容</h4>
        <div className="mt-1 space-y-1">
          {lockedNodesList.map(([nodeId, user]) => (
            <div key={nodeId} className="flex items-center gap-2 text-xs">
              <Avatar className="h-5 w-5">
                {user.image ? (
                  <AvatarImage src={user.image} alt={user.name} />
                ) : (
                  <AvatarFallback>{getUserInitials(user.name)}</AvatarFallback>
                )}
              </Avatar>
              <span>{user.name} 正在编辑</span>
            </div>
          ))}
        </div>
      </div>
    );
  };

  return (
    <div className={`space-y-3 ${className}`}>
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-medium">协作状态</h3>
        {renderConnectionStatus()}
      </div>
      
      <div>
        <h4 className="text-sm font-medium mb-2">在线用户</h4>
        {renderActiveUsers()}
      </div>
      
      {renderLockedNodes()}
    </div>
  );
} 